import gdata.alt.appengine
import gdata.auth
import gdata.service 
import gdata.health
import gdata.health.service
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import os, re, time, string
import urllib2, logging, base64
import simplejson

H9_AUTHSUB_HANDLER = 'https://www.google.com/h9/authsub'
H9_SCOPE = 'https://www.google.com/h9/feeds/'
H9_NEXT_URI = 'https://chiefmedicalofficer.appspot.com/authsub'
AUTHSUB_PARMS = '&permission=1'
if os.environ.get('SERVER_SOFTWARE','').startswith('Devel'):
   H9_NEXT_URI = 'http://localhost:8106/authsub'
   AUTHSUB_PARMS = '&secure=0&permission=1'
else:
   H9_NEXT_URI = 'https://chiefmedicalofficer.appspot.com/authsub'

GDATA_RESOURCE = "https://www.google.com/health/feeds/profile/default"
ACCESS_TOKEN_SETTINGS_URL = 'https://www.google.com/health/AuthenticationTokenSettings'
	
# http://code.google.com/apis/gdata/authsub.html#Registered
H9_RSA_KEY="""-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQCoRrO3oQl2ujFhMLC9RDoERIEAqpc6BnSvtr4RTNQk/520ae42
vT5XtUr8UJ6vULnhokk/1ZX7KlDuw28bkfnS3QgrXaLHY1vClaoeMJkwqlXIDUEC
HfKHsH+Meo3NhrXMXTpYwuNghgAL4nrXP7uIbqtfV9isOLqREMy6zvKJTwIDAQAB
AoGBAKZ1Uf/6576vjntCzAJdhDqGfUnodjHrAvByh+/bHRwAU8OM6hzx9MKUTrnr
Eh4Ab+/YNjdUE8nh4S9e2gDe1M18NbCXKJ/RGbCutMqjUUz7FsOPbD4Vbt5WtO8p
UHY4gjZJE26L3HvsX0Xt8aqOgvwe7KdPbOfIWkM/9ovfK3tRAkEA0p4JTvDYJ3sr
x3gUBog7QYPS5H1/jp/EH1fe36I7U0pU2rYuREsVfRr3RSmSoyeo/qQb8mzKlumo
oTofYjYVGQJBAMyJEK7dD1vfcdzF0vV+1Y52KwNOQj0CfBYrwgEB4kmgXMx1qM8l
udkS0J5QbMhXMTj8emAuMQ3mXBO3IHJjtqcCQCwqhcsvCDTnSFvw20ovYTWw3hWa
F5ih+i+UbqE41PX3XWnr0DH0CNKOSBIR0LU0COU1JsMkeytAXmNI2/HtY2kCQQCi
1XA5tnY2z0In4DpeBbbg7wS5YgFr7uF5CScvhB9yPEAE6psVJ1S5E7iQgTjJmlju
pFqM3dlh1oZxj7Y+O1I7AkEAxgwb0ASHLg8b8Cs6Gqpe+9rmViARPLIzUCb7UJd4
PRgLydIWwWD5PHeEbM/Nvn+gliHkGj5hthssT/h5XtPIiQ==
-----END RSA PRIVATE KEY-----"""

from base import BaseRequestHandler
from handlers import * 
from ghealth import *

class AuthSubURLRequestHandler(BaseRequestHandler):
	def get(self):
		client = gdata.health.service.HealthService(source='chiefmedicalofficer-v1', use_h9_sandbox=True)	
		gdata.alt.appengine.run_on_appengine(client)
		# Generate an AuthSub request URI
		authsuburi = gdata.service.GenerateAuthSubRequestUrl(
			H9_NEXT_URI, [H9_SCOPE], hd='default', secure=True, session=True, 
			request_url=H9_AUTHSUB_HANDLER, include_scopes_in_next=True)
		authsuburi += AUTHSUB_PARMS
		self.response.out.write(authsuburi)

class AuthSubLoginHandler(BaseRequestHandler):
	def get(self):
		
		user = users.get_current_user()
		
		client = gdata.health.service.HealthService(source='chiefmedicalofficer-v1', use_h9_sandbox=True)	
		gdata.alt.appengine.run_on_appengine(client)
		# Attempt to extract an AuthSub token from the current URI
		token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri, rsa_key=H9_RSA_KEY)
		
		if not token:
			# Generate an AuthSub request URI
			authsuburi = gdata.service.GenerateAuthSubRequestUrl(
				H9_NEXT_URI, [H9_SCOPE], hd='default', secure=True, session=True, 
				request_url=H9_AUTHSUB_HANDLER, include_scopes_in_next=True)
			authsuburi += AUTHSUB_PARMS
			self.render_response('index_public', {'login_url': authsuburi, 'username':user.nickname()}) 
		
		else:
			view_vals = {'single_token': str(token), 'health_info': '', 'msg': ''}
			#logging.info("Before upgrade token is %s" % token) 
			client.UpgradeToSessionToken(token)
			#logging.info("After upgrade token is %s" % token) 
			view_vals['auth_token'] = client.AuthSubTokenInfo()  
			view_vals['session_token'] = client.GetAuthSubToken()
			if True:
				gdata.alt.appengine.run_on_appengine(client)
				#params = {'digest': 'true', 'strict': 'true'} 
				params = {'strict': 'true'} 
				query = gdata.health.service.HealthProfileQuery(service='h9', params=params)
				#logging.info("ProfileQueryURI is %s"%query.ToUri())
				profile_feed = client.GetProfileFeed(query)
				
				ccrreader = GoogleHealthCCRReader(profile_feed)
				
				#view_vals['profile_feed'] = profile_feed
				view_vals['medications']  = ccrreader.get_medications() 
				view_vals['conditions']   = ccrreader.get_conditions()
				view_vals['immunizations']= ccrreader.get_immunizations()
				view_vals['procedures']   = ccrreader.get_procedures()   
				view_vals['test_results'] = ccrreader.get_test_results()   
				view_vals['demographics'] = ccrreader.get_demographics()
				
				self.render_response('index', view_vals)
				#self.response.out.write(simplejson.dumps(view_vals))
			try:
				pass
			except Exception, e:
				logging.error(e)
				view_vals['msg'] = e
				self.render_response('index', view_vals)
				#client.RevokeAuthSubToken()
				#self.redirect('/revoke')
			
		

def main():

	urls = [('/', AuthSubLoginHandler),
			('/authsub', AuthSubLoginHandler),
			('/profiles', ProfileHandler),
			('/revoke', RevokeRegistration),
			('/maps', MapHandler),
			('/browse', BrowseHandler), 
			('/mobile', MobileHandler),
			('/about', AboutHandler),
			('/getauthsuburl', AuthSubURLRequestHandler),
			('/conditions', StaticConditionHandler)
		   ]
	
	application = webapp.WSGIApplication(urls, debug=True)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
